//
//  LTHTTPTool.m
//  LTIM
//
//  Created by 俊松何 on 2017/3/30.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTHTTPTool.h"
#import "CommonCrypto/CommonDigest.h"
#import "AFNetworking.h"
#import "LTBaseDataModel.h"
#import "LTError.h"
#import "LTClient.h"
#import "LTUser.h"
#import <AliyunOSSiOS/OSSService.h>
#import "LTAESTool.h"



static NSString *apiURL = @"https://fanyi-api.baidu.com/api/trans/vip/translate";
static NSInteger appID = 20170808000071258;
static NSString *secretKey = @"t9XKz89b8r3gqkwp8Uhd";

@interface LTHTTPTool()

@property(nonatomic,strong) AFHTTPSessionManager *manager;

@property(nonatomic,strong) AFURLSessionManager *sessionManager;


@end



static LTHTTPTool *lttool=nil; //放入外部
@implementation LTHTTPTool

+(instancetype)shareTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lttool  = [[LTHTTPTool alloc] init];
        lttool.manager = [AFHTTPSessionManager manager];
        lttool.manager.operationQueue.maxConcurrentOperationCount = 5;
        lttool.manager.requestSerializer.timeoutInterval = 20;
        lttool.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        lttool.manager.responseSerializer = [AFJSONResponseSerializer serializer];
        lttool.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html",@"text/javascript", nil];
        [lttool.manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [lttool.manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"platform"];
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        // app版本
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        [lttool.manager.requestSerializer setValue:app_Version forHTTPHeaderField:@"versionName"];
        [lttool.manager.requestSerializer setValue:[LTClient sharedClient].appId forHTTPHeaderField:@"appid"];
        
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        NSArray* languages = [def objectForKey:@"AppleLanguages"];
        NSString *current = [languages objectAtIndex:0];
        [lttool.manager.requestSerializer setValue:current forHTTPHeaderField:@"language"];
        NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [lttool.manager.requestSerializer setValue:uuid forHTTPHeaderField:@"uuid"];
        lttool.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        lttool.sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        
    });
    return lttool;
}




-(NSURLSessionDataTask *)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(ltsuccess)success parmerror:(ltparmerror)parmerror failer:(ltfailer)failer
{
    
    if([LTClient sharedClient].currentUserId != nil){
        [lttool.manager.requestSerializer setValue:[LTClient sharedClient].currentUserId forHTTPHeaderField:@"userId"];
        NSDictionary *dict = @{
                               @"userId":[LTClient sharedClient].currentUserId,
                               @"token":[LTClient sharedClient].currentUser.xToken
                               };
        NSString *jsonstr = [dict mj_JSONString];
        NSString *invadStr = [LTAESTool registerEncryptAES:jsonstr];
        
        [lttool.manager.requestSerializer setValue:invadStr forHTTPHeaderField:@"xtoken"];
    }
    NSString *fullpath = [NSString stringWithFormat:@"%@%@",basePath,path];
    
    DLog(@"请求信息 -->\n"
         "URL:  %@\n"
         "fullpath:  %@\n"
         "Headers:\n%@\n"
         "Parameters:\n%@\n",
         basePath, fullpath, lttool.manager.requestSerializer.HTTPRequestHeaders,
         parameters);
    
    NSURLSessionDataTask *task =  [_manager POST:fullpath parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        LTBaseDataModel *model = [LTBaseDataModel mj_objectWithKeyValues:responseObject];
        DLog(@"Response  -->\n response object:\n%@\n",
             responseObject);
        
        
        if(model.code == 1)
        {
            success(model);
        }else if(model.code == 400 || model.code == 401)
        {
            parmerror(model);
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginTokenError object:model.message];
        }
        else
        {
            parmerror(model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failer(error);
        
        DLog(@"Response  -->\n"
             "URL:  %@\n"
             "error:\n%@\n",
             task.currentRequest.URL, error);
    }];
    return task;
}


-(NSURLSessionDataTask *)getPath:(NSString *)path parameters:(NSDictionary *)parameters success:(ltsuccess)success parmerror:(ltparmerror)parmerror failer:(ltfailer)failer
{
    NSString *fullpath = [NSString stringWithFormat:@"%@%@",basePath,path];
    if([LTClient sharedClient].currentUserId != nil){
        [lttool.manager.requestSerializer setValue:[LTClient sharedClient].currentUserId forHTTPHeaderField:@"userId"];
        NSDictionary *dict = @{
                               @"userId":[LTClient sharedClient].currentUserId,
                               @"token":[LTClient sharedClient].currentUser.xToken
                               };
        NSString *jsonstr = [dict mj_JSONString];
        NSString *invadStr = [LTAESTool registerEncryptAES:jsonstr];
        
        [lttool.manager.requestSerializer setValue:invadStr forHTTPHeaderField:@"xtoken"];
    }
    DLog(@"请求信息 -->\n"
         "URL:  %@\n"
         "fullpath:  %@\n"
         "Headers:\n%@\n"
         "Parameters:\n%@\n",
         basePath, fullpath, lttool.manager.requestSerializer.HTTPRequestHeaders,
         parameters);

    
    NSURLSessionDataTask *task =  [_manager GET:fullpath parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LTBaseDataModel *model = [LTBaseDataModel mj_objectWithKeyValues:responseObject];
        //解析结果
        DLog(@"Response  -->\n response object:\n%@\n",
             responseObject);
        
        if(model.code == 1)
        {
            success(model);
        }else if(model.code == 400 || model.code == 401)
        {
            parmerror(model);
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginTokenError object:model.message];
        }
        else
        {
            parmerror(model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failer(error);
        
        DLog(@"Response  -->\n"
             "URL:  %@\n"
             "error:\n%@\n",
             task.currentRequest.URL, error);
    }];
    return task;
}

-(NSURLSessionDataTask *)lt_postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(ltsuccess)success parmerror:(ltparmerror)parmerror failer:(ltfailer)failer
{
    
    NSURLSessionDataTask *task =  [_manager POST:path parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LTBaseDataModel *model = [LTBaseDataModel mj_objectWithKeyValues:responseObject];
        if(model.code == 1)
        {
            success(model);
        }else
        {
            parmerror(model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failer(error);
    }];
    return task;
}


-(NSURLSessionDataTask *)lt_getPath:(NSString *)path parameters:(NSDictionary *)parameters success:(ltsuccess)success parmerror:(ltparmerror)parmerror failer:(ltfailer)failer
{
    
    
    NSURLSessionDataTask *task =  [_manager GET:path parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LTBaseDataModel *model = [LTBaseDataModel mj_objectWithKeyValues:responseObject];
        if(model.code == 1)
        {
            success(model);
        }else
        {
            parmerror(model);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failer(error);
    }];
    return task;
}



-(NSURLSessionDataTask *)deletePath:(NSString *)path parameters:(NSDictionary *)parameters success:(ltsuccess)success parmerror:(ltparmerror)parmerror failer:(ltfailer)failer
{
    
    NSString *fullpath = [NSString stringWithFormat:@"%@%@",basePath,path];
    NSURLSessionDataTask *task = [_manager DELETE:fullpath parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LTBaseDataModel *model = [LTBaseDataModel mj_objectWithKeyValues:responseObject];
        if(model.code == 1)
        {
            success(model);
        }else
        {
            parmerror(model);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failer(error);
    }];
    return task;
}


-(void)getUploadTokenWithType:(FileType)type success:(void(^)(LTFileTokenModel *model))success failer:(void(^)(LTError *lterror))failer
{
    
    NSTimeInterval time_stamp = [[NSDate date] timeIntervalSince1970];
    NSInteger time_senonds = time_stamp;
    NSString *md5str = [self MD5StringForString:[NSString stringWithFormat:@"%@%d%ld",md5key,type,time_senonds]];
    
    NSDictionary *param = @{@"type":@(type),
                            @"time_stamp":@(time_senonds),
                            @"fileName":md5str,
                            };
    [self getPath:@"/commons/upload/get_info" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        LTFileTokenModel *tokenModel = [LTFileTokenModel mj_objectWithKeyValues:datamodel.data];
        success(tokenModel);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:(int)datamodel.code];
        failer(lterror);
        
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        failer(lterror);
    }];
}

//得到网易文件的token
-(void)getUploadTokenWithType:(FileType)type
                     fileName:(NSString *)fileName
                      success:(void(^)(LTFileTokenModel *model))success
                       failer:(void(^)(LTError *lterror))failer
{

    NSDictionary *param = @{@"type":@(type),
                            @"fileName":fileName,
                            };
    [self getPath:@"/commons/upload/get_wy_info" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        LTFileTokenModel *tokenModel = [LTFileTokenModel mj_objectWithKeyValues:datamodel.data];
        success(tokenModel);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:(int)datamodel.code];
        failer(lterror);
        
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        failer(lterror);
    }];
    
    
}



-(void)uploadFileData:(NSData *)data
             FileType:(FileType)type
             progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))uploadProgress
              success:(void(^)(NSString *fileUrl,LTFileTokenModel *model))success
               failer:(void(^)(LTError *lterror))failer
{
    
    NSString *suffix = nil;
    switch (type) {
        case FileTypeNormal: suffix = @"jpg";break;
        case FileTypeVoice:  suffix = @"amr";break;
        case FileTypeVideo:  suffix = @"mp4";break;
        default:  break;
    }
    
    NSString *objectName = [self fileNameWithSuffix:suffix];
    [self getUploadTokenWithType:type  success:^(LTFileTokenModel *model) {

        NSString *failePath =  [NSTemporaryDirectory() stringByAppendingString:objectName];
        [[NSFileManager defaultManager] createFileAtPath:failePath contents:data attributes:nil];
        model.objectKey = objectName;
        
        id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:model.access_key_id secretKeyId:model.access_key_secret securityToken:model.token];
        
        OSSClient *client = [[OSSClient alloc] initWithEndpoint:model.oss_end_point credentialProvider:credential];
        
        
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
        
        put.bucketName = model.bucket_name;
        put.objectKey = model.objectKey;
        
        put.uploadingData = data;
        
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//            int currentPercent = percent * 100;
            uploadProgress(bytesSent,totalByteSent,totalBytesExpectedToSend);
        };
        
        OSSTask * putTask = [client putObject:put];
        
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSLog(@"upload object success!");
                 success([NSString stringWithFormat:@"%@%@",model.oss_url,objectName],model);
            } else {
                NSLog(@"upload object failed, error: %@" , task.error);
                LTError *lterror = [LTError errorWithDescription:@"upload object failed" code:-1];
                failer(lterror);
            }
            return nil;
        }];
        
    } failer:^(LTError *lterror) {
        failer(lterror);
    }];
    
}


-(void)uploadImageData:(NSData *)data
              progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))uploadProgress
               success:(void(^)(NSString *remotePath,LTFileTokenModel *model))success
                failer:(void(^)(LTError *lterror))failer
{
    
    NSString *objectName = [self fileNameWithSuffix:@"jpg"];
    
    [self getUploadTokenWithType:FileTypeNormal  success:^(LTFileTokenModel *model) {
        
        NSString *failePath =  [NSTemporaryDirectory() stringByAppendingString:objectName];
        [[NSFileManager defaultManager] createFileAtPath:failePath contents:data attributes:nil];
        model.objectKey = objectName;
        
        id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:model.access_key_id secretKeyId:model.access_key_secret securityToken:model.token];
        
        OSSClient *client = [[OSSClient alloc] initWithEndpoint:model.oss_end_point credentialProvider:credential];
        
        
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
        
        put.bucketName = model.bucket_name;
        put.objectKey = objectName;
        
        put.uploadingData = data;
        
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
            if(uploadProgress != nil)
            {
               uploadProgress(bytesSent,totalByteSent,totalBytesExpectedToSend);
            }
        };
        
        OSSTask * putTask = [client putObject:put];
        
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSLog(@"upload object success!");
                success([NSString stringWithFormat:@"%@%@",model.oss_url,objectName],model);
            } else {
                NSLog(@"upload object failed, error: %@" , task.error);
                LTError *lterror = [LTError errorWithDescription:@"upload object failed" code:-1];
                failer(lterror);
            }
            return nil;
        }];
    } failer:^(LTError *lterror) {
         failer(lterror);
    }];
}

#pragma mark - 上传多张图片方法
-(void)uploadImages:(NSArray *)images
           complete:(void(^)(NSArray<NSString *> *names, BOOL state))complete {
    

    NSInteger count = images.count;
    NSMutableArray *urls = [NSMutableArray arrayWithCapacity:4];
    __block int successCount = 0;
    
    for (int i = 0; i < count; i++) {
       
        NSData *data = UIImageJPEGRepresentation(images[i], 0.3);
        [self uploadImageData:data progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            
        } success:^(NSString *fileUrl, LTFileTokenModel *model) {
            successCount = successCount + 1;
            [urls addObject:fileUrl];
            if(successCount == count)
            {
                complete(urls,YES);
            }
        } failer:^(LTError *lterror) {
            
            complete(urls,NO);
            
        }];
        
    }
    
}


-(void)downloadVoiceData:(LTFileTokenModel *)ossmodle
                progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))downloadProgress
                 success:(void(^)(NSData *data))success
                  failer:(void(^)(LTError *lterror))failer
{
    
    NSString *file = [NSString stringWithFormat:@"%@%@",ossmodle.oss_url,ossmodle.objectKey];
    
    [self downloadFile:file suffix:@"amr" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
    } success:success failer:failer];

}


-(void)downloadImageData:(LTFileTokenModel *)ossmodle
             isthumbnail:(BOOL)isthumbnail
                progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))downloadProgress
                 success:(void(^)(NSData *data))success
                  failer:(void(^)(LTError *lterror))failer
{
    NSString *thumbnail =  @"";
    if(isthumbnail)
    {
        thumbnail = @"?imageView&thumbnail=200x200";
    }
    
    NSString *file = [NSString stringWithFormat:@"%@%@%@",ossmodle.oss_url,ossmodle.objectKey,thumbnail];
    
    [self downloadFile:file suffix:@"jpg" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
    } success:success failer:failer];
}



-(void)downloadVideoData:(LTFileTokenModel *)ossmodle
                progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))downloadProgress
                 success:(void(^)(NSData *data))success
                  failer:(void(^)(LTError *lterror))failer
{
    NSString *file = [NSString stringWithFormat:@"%@%@",ossmodle.oss_url,ossmodle.objectKey];
    
    [self downloadFile:file suffix:@"mp4" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
    } success:success failer:failer];
}

-(void)downloadFileData:(LTFileTokenModel *)ossmodle
               progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))downloadProgress
                success:(void(^)(NSData *data))success
                 failer:(void(^)(LTError *lterror))failer
{
    
    NSString *file = [NSString stringWithFormat:@"%@%@",ossmodle.oss_url,ossmodle.objectKey];
    
    NSArray *tempArray = [ossmodle.objectKey componentsSeparatedByString:@"."];
    NSString *sufix = @"";
    
    if(tempArray.count >=1)
    {
        sufix = tempArray.lastObject;
    }
    
    [self downloadFile:file suffix:sufix progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
    } success:success failer:failer];
}

-(void)downloadFile:(NSString *)filePath
             suffix:(NSString *)suffix
           progress:(void(^)(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend))progress
            success:(void(^)(NSData *data))success
             failer:(void(^)(LTError *lterror))failer
{
    
    
    NSString *tempPath = [self fileTempPathWithSuffix:suffix];
    NSURLSessionDownloadTask *task  =   [_sessionManager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:filePath]] progress:^(NSProgress * _Nonnull downloadProgress) {
        NSInteger currentprogress = downloadProgress.fractionCompleted * 100;
        progress(0,currentprogress,100);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:tempPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if(error == nil)
        {
            NSData *data = [NSData dataWithContentsOfURL:filePath];
            success(data);
        }else
        {
            failer([LTError errorWithDescription:error.domain code:error.code]);
        }
    }];
    [task resume];
    
}


-(void)getSelfUserInfoWithCompletion:(void(^)(LTUser *user,LTError *lterror))completionblock

{
    NSString *fullpath = [NSString stringWithFormat:@"%@%@",basePath,@"/user/get_info"];
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    if(userId != nil){
        [lttool.manager.requestSerializer setValue:[LTClient sharedClient].currentUserId forHTTPHeaderField:@"userId"];
    }

   [_manager GET:fullpath parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LTBaseDataModel *model = [LTBaseDataModel mj_objectWithKeyValues:responseObject];
        NSString* jsonStr = [responseObject mj_JSONString];
        //解析结果
        DLog(@"Response  -->\n response object:\n%@\n, json data:\n%@\n",
             responseObject, jsonStr);
        
        if(model.code == 1)
        {
            LTUser *user = [LTUser mj_objectWithKeyValues:model.data];
            
            completionblock(user,nil);
        }else
        {
            completionblock(nil,[LTError errorWithDescription:model.message code:model.code]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completionblock(nil,[LTError netWorkError]);
        
    }];

}

-(void)getAppInfoComplete:(void(^)(BOOL needUpate,LTError *error))completeBlock
{
    
    //2先获取当前工程项目版本号
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    NSString*currentVersion=infoDic[@"CFBundleShortVersionString"];
    
    AFHTTPSessionManager *manger =   [AFHTTPSessionManager manager];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html",@"text/javascript", nil];
    [manger.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    [manger GET:@"http://itunes.apple.com/lookup?id=1273663204" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(responseObject != nil)
        {
            NSArray *array = responseObject[@"results"];
            NSDictionary *dic =  array[0];
            NSString *appStoreVersion = dic[@"version"];
            
            NSString *currentVersionS = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@"0"];
            NSString *appStoreVersionS = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@"0"];
            
            NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersionS,appStoreVersionS);
            if([currentVersionS floatValue] <[appStoreVersionS floatValue])
            {
                completeBlock(YES,nil);
            }else
            {
                completeBlock(NO,nil);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completeBlock(NO,[LTError netWorkError]);
    }];
    
}


//void(^translateBlock)(NSString * result, LTError *error);

-(void)translateWith:(NSString *)string to:(NSString *)des result:(void(^)(NSString * result, LTError *error))completeBlock
{
    
    //随机数
    NSUInteger salt = arc4random();
    //拼接字符串
    NSString *sign = [NSString stringWithFormat:@"%@%@%zd%@",@(appID),string,salt,secretKey];
    //MD5加密
    NSString *signMd5 = [[LTHTTPTool shareTool] MD5StringForString:sign];
    //请求所需参数
    NSDictionary *dic = @{@"q":string,
                          @"from":@"auto",
                          @"to":des,
                          @"appid":@(appID),
                          @"salt":@(salt),
                          @"sign":signMd5};
    
    [[AFHTTPSessionManager manager] POST:apiURL parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray * result = responseObject[@"trans_result"];
        if (responseObject[@"from"] != nil) {
            completeBlock(result[0][@"dst"], nil);
        }else{
            LTError * error =[LTError errorWithDescription:responseObject[@"error_msg"] code:[responseObject[@"error_code"] integerValue]];
            completeBlock(nil,error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        completeBlock(nil,[LTError netWorkError]);
    }];
    
}



-(NSString *)MD5StringForString:(NSString *)str{
    
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
    
}

//文件命名
-(NSString *)fileNameWithSuffix:(NSString *)suffix
{
    //随机数
    int rand = arc4random() % 1000;
    long filename = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *objectName = [NSString stringWithFormat:@"%d%ld.%@",rand,filename,suffix];
    return objectName;
}

//下载文件临时存放路径
-(NSString *)fileTempPathWithSuffix:(NSString *)suffix
{
    NSString *filename = [self fileNameWithSuffix:suffix];
    NSString *filePath =  [NSTemporaryDirectory() stringByAppendingString:filename];
    return filePath;
}



@end
